package com.ocom.webapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.ocom.common.constant.MapKey;
import com.ocom.common.entity.aiot.EntityXfDeviceInfo;
import com.ocom.common.request.payconfig.AddConsDeviceInfoRequest;
import com.ocom.common.request.payconfig.DeleteConsDeviceInfoRequest;
import com.ocom.common.request.web.ConsumeDeviceAddRequest;
import com.ocom.common.request.web.ConsumeDeviceDeleteRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.security.utils.SecurityUtils;
import com.ocom.webapi.feign.AiotClientService;
import com.ocom.webapi.feign.DeviceHttpClientService;
import com.ocom.webapi.feign.PayConfigClientService;
import com.ocom.webapi.service.ConsumeDeviceService;
import com.ocom.webapi.vo.consumedevice.OnShowVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.hutool.poi.excel.cell.CellUtil.getCellValue;

@Slf4j
@Service
public class ConsumeDeviceServiceImpl implements ConsumeDeviceService {

    @Autowired
    private AiotClientService aiotClientService;

    @Autowired
    private DeviceHttpClientService deviceHttpClientService;

    @Autowired
    private PayConfigClientService payConfigClientService;

    //2.4.3消费设备新增（ConsumeDevice/add）
    @Override
    public Result ConsumeDeviceAdd(ConsumeDeviceAddRequest request) {
//        Map<String, Object> map = new HashMap<>();
//        MapKey mapKey = new MapKey();
//        map.put(mapKey.getKey_saasNo(),1);
//        map.put(mapKey.getKey_agentId(),SecurityUtils.getYoCiUser().getComId());
//        map.put(mapKey.getKey_comId(),request.getComId());
//        map.put(mapKey.getKey_deviceNo(),request.getDeviceNo());
//        map.put(mapKey.getKey_status(),1);
//        Result result = deviceHttpClientService.SetDeviceActBySaas(map);

        request.setDeviceNo(request.getDeviceNo().trim());

        Map<String, Object> map = new HashMap<>();
        map.put("saasNo",1);
        map.put("agentId",SecurityUtils.getYoCiUser().getComId());
        map.put("comId",request.getComId());
        map.put("deviceNo",request.getDeviceNo());
        map.put("status",1);
        Result result = aiotClientService.SetXfDeviceStatusBySaas(map);
        if (result.getCode()!=200){
            ResultUtil.error(result.getCode());
        }

        EntityXfDeviceInfo xfDeviceInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityXfDeviceInfo.class);
        if (xfDeviceInfo == null){
            log.error("消费失败解析数据失败 【{}】" ,result);
            return result;
         //   return ResultUtil.error(ResultEnum.Err_3023,"消费失败解析数据失败");
        }

        AddConsDeviceInfoRequest addConsDeviceInfoRequest=new AddConsDeviceInfoRequest();
        addConsDeviceInfoRequest.setComId(request.getComId());
        addConsDeviceInfoRequest.setAiotNo(request.getAiotNo());
        addConsDeviceInfoRequest.setDeviceNo(request.getDeviceNo());
        addConsDeviceInfoRequest.setDeviceName(request.getDeviceName());
        addConsDeviceInfoRequest.setPointId(0);
        addConsDeviceInfoRequest.setDeviceType(Math.toIntExact(xfDeviceInfo.getDeviceType()));
        addConsDeviceInfoRequest.setDeviceVerType(Math.toIntExact(xfDeviceInfo.getDeviceVerType()));
        addConsDeviceInfoRequest.setDeviceMode(request.getDeviceMode());
        addConsDeviceInfoRequest.setAppVer(xfDeviceInfo.getAppVer());
        addConsDeviceInfoRequest.setRemark(request.getRemark());
        addConsDeviceInfoRequest.setCreateUser(SecurityUtils.getUsername());
        addConsDeviceInfoRequest.setConsType(request.getConsType());
        return payConfigClientService.addConsDeviceInfo(addConsDeviceInfoRequest);
    }

    //2.4.6消费设备删除（ConsumeDevice/delete）
    @Override
    public Result ConsumeDeviceDelete(ConsumeDeviceDeleteRequest request) {

        DeleteConsDeviceInfoRequest deleteConsDeviceInfoRequest=new DeleteConsDeviceInfoRequest();
        String[] deviceNos = request.getDeviceNo().split(",");
        List<Object> list = new ArrayList<>();


        for (String deviceNo: deviceNos) {
            Map<String,Object>  objectMap =new HashMap<>();
            objectMap.put("deviceNo",deviceNos);
//            Map<String, Object> map = new HashMap<>();
//            MapKey mapKey = new MapKey();
//            map.put(mapKey.getKey_saasNo(),1);
//            map.put(mapKey.getKey_agentId(),0);
//            map.put(mapKey.getKey_comId(),request.getComId());
//            map.put(mapKey.getKey_deviceNo(),deviceNo);
//            map.put(mapKey.getKey_status(),0);
//            Result result = deviceHttpClientService.SetDeviceUnActBySaas(map);
//            if (result.getCode()!=200){
//                ResultUtil.error(result.getCode());
//            }
            Map<String, Object> map = new HashMap<>();
            map.put("saasNo",1);
            map.put("agentId",0);
            map.put("comId",request.getComId());
            map.put("deviceNo",deviceNo);
            map.put("status",0);
            Result result = aiotClientService.SetXfDeviceStatusBySaas(map);
            if (result.getCode()!=200){
                objectMap.put("msg",result.getMsg());
                list.add(objectMap);
            }

            deleteConsDeviceInfoRequest.setCom_id(request.getComId());
            deleteConsDeviceInfoRequest.setDevice_no(deviceNo);
            Result result1=payConfigClientService.deleteConsDeviceInfo(deleteConsDeviceInfoRequest);
            if (result1.getCode()==200){
                objectMap.put("msg","成功");
                list.add(objectMap);
            }
        }
        return ResultUtil.success(list);
    }

    //2.4.1消费设备列表（ConsumeDevice/onShow）
    @Override
    public Result ConsumeDeviceOnShow(OnShowVo onShowVo) {
        Map<String, Object> map = new HashMap<>();
        MapKey mapKey = new MapKey();
        map.put(mapKey.getKey_comId(),onShowVo.getComId());
        map.put(mapKey.getKey_deviceNo(),onShowVo.getDeviceNo());
        map.put(mapKey.getKey_deviceName(),onShowVo.getDeviceName());
        map.put(mapKey.getKey_deviceType(),onShowVo.getDeviceType());
        map.put(mapKey.getKey_deviceType(),onShowVo.getDeviceType());
        map.put(mapKey.getKey_deviceType(),onShowVo.getDeviceType());
        map.put(mapKey.getKey_deviceVerType(),onShowVo.getDeviceVerType());
        map.put(mapKey.getKey_status(),onShowVo.getStatus());
        map.put(mapKey.getKey_deviceMode(),onShowVo.getDeviceMode());
        map.put(mapKey.getKey_appVer(),onShowVo.getAppVer());
        map.put(mapKey.getKey_page(),onShowVo.getPage());
        map.put(mapKey.getKey_size(),onShowVo.getSize());

        return payConfigClientService.GetConsDeviceList(map);
    }

    // 导入消费设备（ConsumeDevice/import）
    @Override
    public Result ConsumeDeviceImport(Long comId,  MultipartFile file) {


        //        1、用HSSFWorkbook打开或者创建“Excel文件对象”
        //        2、用HSSFWorkbook对象返回或者创建Sheet对象
        //        3、用Sheet对象返回行对象，用行对象得到Cell对象
        //        4、对Cell对象读写。
        //获得文件名
        Workbook workbook = null ;
        String fileName = file.getOriginalFilename();
        if(fileName.endsWith("xls")){
            //2003
            try {
                workbook = new HSSFWorkbook(file.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if(fileName.endsWith("xlsx")){
            //2007
            try {
                workbook = new XSSFWorkbook(file.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                throw new Exception("文件不是Excel文件");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Sheet sheet = workbook.getSheetAt(0);
        int rows = sheet.getLastRowNum();// 指的行数，一共有多少行+
        if(rows==0){
            try {
                throw new Exception("请填写数据");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Integer actSuccessCount =0;
        Integer actErrorCount =0;
        Integer successCount=0;
        Integer errorCount=0;
        List<String> list = new ArrayList<>();
        for (int i = 1; i < rows+1; i++) {
            Map<String, Object> map = new HashMap<>();
            MapKey mapKey = new MapKey();
            map.put(mapKey.getKey_saasNo(),1);
            map.put(mapKey.getKey_agentId(),SecurityUtils.getYoCiUser().getComId());
            map.put(mapKey.getKey_comId(),comId);

            map.put(mapKey.getKey_status(),1);


            // 读取左端单元格
            Row row = sheet.getRow(i);
            // 行不为空
            String deviceNo = null;
            if (row != null) {

                // **读取cell**
                //设备编号
                deviceNo = JSON.toJSONString(getCellValue(row.getCell(0)));
                map.put(mapKey.getKey_deviceNo(),deviceNo);

            }
            try {
                Result result = deviceHttpClientService.SetDeviceActBySaas(map);
                if(result.getCode()==200){
                    actSuccessCount++;
                }else {
                    list.add(deviceNo);
                    actErrorCount++;
                }
                EntityXfDeviceInfo xfDeviceInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityXfDeviceInfo.class);
                if (xfDeviceInfo == null){
                    log.error("消费设备数据不存在或者解析数据失败"+result);
                    continue;
                }
                AddConsDeviceInfoRequest addConsDeviceInfoRequest=new AddConsDeviceInfoRequest();
                addConsDeviceInfoRequest.setComId(comId);
                addConsDeviceInfoRequest.setDeviceNo(deviceNo);
                addConsDeviceInfoRequest.setPointId(0);
                addConsDeviceInfoRequest.setDeviceType(Math.toIntExact(xfDeviceInfo.getDeviceType()));
                addConsDeviceInfoRequest.setDeviceVerType(Math.toIntExact(xfDeviceInfo.getDeviceVerType()));
                addConsDeviceInfoRequest.setAppVer(xfDeviceInfo.getAppVer());
                addConsDeviceInfoRequest.setCreateUser(SecurityUtils.getUsername());
                Result result1 = payConfigClientService.addConsDeviceInfo(addConsDeviceInfoRequest);
                if(result1.getCode()==200){
                    successCount++;
                }else {
                    list.add(deviceNo);
                    errorCount++;
                }

            }catch (Exception exception){
                exception.printStackTrace();
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("actSuccessCount",actSuccessCount);
        map.put("actErrorCount",actErrorCount);
        map.put("successCount",successCount);
        map.put("errorCount",errorCount);
        map.put("deviceNos",list);
        return ResultUtil.success(map);
    }
}
